<template>
  <div>
    <!-- 主列表页面 -->
    <div v-if="!showEditPage && !showProcessPage">
      <a-card :body-style="{ height: 'calc(100vh - 125px)' }">
        <a-row class="w-full h-full flex flex-col overflow-x-auto overflow-y-hidden">
          <!-- 查询条件 -->
          <a-row v-if="showSearchRow" class="w-full">
            <a-form :model="searchForm" label-align="left" layout="inline" size="small">
               <a-form-item field="projectName" label="项目名称">
                <a-input
                    v-model="searchForm.projectName"
                    allow-clear
                    placeholder="请输入项目名称"
                />
              </a-form-item>
              <a-form-item field="projectType" label="项目类型">
                <a-select
                    v-model="searchForm.projectType"
                    allow-clear
                    placeholder="请选择项目类型"
                >
                  <a-option 
                    v-for="(d, index) in dicts[proxy.DICT.lindiProjectType]" 
                    :key="index" 
                    :label="d.dictValue" 
                    :value="d.dictKey"
                  >
                  </a-option>
                </a-select>
              </a-form-item>
              <a-form-item field="tradeStatus" label="交易状态">
                <a-select
                    v-model="searchForm.tradeStatus"
                    allow-clear
                    placeholder="请选择交易状态"
                >
                  <a-option v-for="item in tradeStatusList" :key="item.code" :value="item.code">
                    {{ item.desc }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-form>
            <a-row class="w-full mt-2" justify="center">
              <a-space>
                <a-button type="primary" @click="search">
                  <template #icon>
                    <icon-search/>
                  </template>
                  <template #default>查询</template>
                </a-button>
                <a-button @click="reset">
                  <template #icon>
                    <icon-refresh/>
                  </template>
                  <template #default>重置</template>
                </a-button>
              </a-space>
            </a-row>
          </a-row>

          <!-- 分割线 -->
          <a-divider v-if="showSearchRow" class="mt-2"/>

          <!-- 数据操作区 -->
          <a-row class="w-full flex justify-between">
            <a-space>
              <!-- 添加 -->
              <a-button
                  size="small"
                  type="primary"
                  @click="handleAdd"
              >
                <template #icon>
                  <icon-plus/>
                </template>
                <template #default>新增</template>
              </a-button>
            </a-space>
            <a-space>
              <!-- 刷新 -->
              <a-button shape="circle" size="small" @click="search">
                <template #icon>
                  <icon-refresh/>
                </template>
              </a-button>
              <!-- 收缩/展开 -->
              <a-button shape="circle" size="small" @click="showSearchRow = !showSearchRow">
                <template #icon>
                  <icon-caret-up v-if="showSearchRow"/>
                  <icon-caret-down v-else/>
                </template>
              </a-button>
            </a-space>
          </a-row>

          <!-- 数据展示区 -->
          <a-row class="w-full flex-1 mt-3 overflow-y-auto">
        <a-table
          row-key="tradeApplicationId"
          :loading="loading"
          :pagination="pagination"
          :columns="columns"
          :data="tableData"
          :bordered="false"
          @page-change="handlePageChange"
          @page-size-change="handlePageSizeChange"
        >
          <template #projectType="{ record }">
            {{ getProjectTypeText(record.projectType) }}
          </template>
          <template #projectAddress="{ record }">
            <div class="address-cell">
              {{ record.projectLocation }}
            </div>
          </template>
          <template #tradeCode="{ record }">
            <div class="code-cell">
              {{ record.tradeCode }}
            </div>
          </template>
          <template #applicationTime="{ record }">
            <div class="time-cell">
              <div>{{ formatDate(record.applicationTime) }}</div>
              <div class="time-detail">{{ formatTime(record.applicationTime) }}</div>
            </div>
          </template>
          <template #tradeStatus="{ record }">
            <a-tag :color="getStatusColor(record.tradeStatus)">
              {{ getStatusText(record.tradeStatus) }}
            </a-tag>
          </template>
          <template #operations="{ record }">
            <div style="display: flex; flex-wrap: wrap; gap: 4px; justify-content: center;">
              <a-button type="text" size="mini" @click="handleEdit(record)">
                <template #icon>
                  <icon-edit />
                </template>
                <template #default>修改</template>
              </a-button>
              <a-button type="text" size="mini" @click="handleProcess(record)">
                <template #icon>
                  <icon-eye />
                </template>
                <template #default>处理</template>
              </a-button>
              <a-popconfirm
                :content="`确定删除【${record.projectName}】吗?`"
                type="warning"
                @ok="onDeleteOK(record.tradeApplicationId)"
              >
                <a-button
                  :loading="deleteLoading"
                  size="mini"
                  status="danger"
                  type="text"
                >
                  <template #icon>
                    <icon-delete />
                  </template>
                  <template #default>删除</template>
                </a-button>
              </a-popconfirm>
            </div>
          </template>
        </a-table>
          </a-row>
        </a-row>
      </a-card>
    </div>

    <!-- 编辑页面 -->
    <div v-if="showEditPage">
      <component 
        :is="TradeApplicationEditPage" 
        :tradeApplicationId="currentTradeApplicationId" 
        @cancel="handleEditCancel" 
        @ok="handleEditOk" 
      />
    </div>

    <!-- 处理页面 -->
    <div v-if="showProcessPage">
      <component 
        :is="TradeApplicationProcess" 
        :tradeApplicationId="currentTradeApplicationId" 
        @cancel="handleProcessCancel" 
        @refresh="handleProcessRefresh" 
      />
    </div>
  </div>
</template>

<script setup>
import { computed,ref, reactive, onMounted, getCurrentInstance } from "vue";
import { Message, Modal } from '@arco-design/web-vue';
import { defineAsyncComponent } from 'vue';
import {
  getPageTradeApplicationListApi,
  deleteTradeApplicationByTradeApplicationIdApi,
} from "~/api/lindi/tradeApplication.js";

// 动态导入组件
const TradeApplicationEditPage = defineAsyncComponent(() => import('./TradeApplicationEditPage.vue'));
const TradeApplicationProcess = defineAsyncComponent(() => import('./TradeApplicationProcess.vue'));

// 全局实例
const { proxy } = getCurrentInstance();

// 字典数据
const dicts = proxy.LoadDicts([proxy.DICT.lindiProjectType, proxy.DICT.lindiTradeStatus]);

// 加载状态
const loading = ref(false);
const submitLoading = ref(false);
const deleteLoading = ref(false);

// 搜索行显示状态
const showSearchRow = ref(true);

// 查询表单
const searchForm = reactive({
  projectName: "",
  projectType: null,
  tradeStatus: null,
});

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  projectName: "",
  projectType: null,
  tradeStatus: null,
});

// 分页信息
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
});

// 表格数据
const tableData = ref([]);

// 交易状态列表 - 使用字典数据
const tradeStatusList = computed(() => {
  return dicts[proxy.DICT.lindiTradeStatus]?.map(item => ({
    code: Number(item.dictKey),
    desc: item.dictValue
  })) || [];
});

// 项目类型列表 - 使用字典数据
const projectTypeList = computed(() => {
  return dicts[proxy.DICT.lindiProjectType]?.map(item => ({
    code: Number(item.dictKey),
    desc: item.dictValue
  })) || [];
});

// 表格列
const columns = [
  {
    title: "项目名称",
    dataIndex: "projectName",
    align: "center",
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "项目地址",
    dataIndex: "projectLocation",
    align: "center",
    slotName: "projectLocation",
    width: 200,
  },
  {
    title: "项目类型",
    dataIndex: "projectType",
    align: "center",
    slotName: "projectType",
  },
  {
    title: "交易指标编号",
    dataIndex: "tradeCode",
    align: "center",
    slotName: "tradeCode",
    width: 180,
  },
  {
    title: "市储备库指标(亩)",
    dataIndex: "reserveArea",
    align: "center",
  },
  {
    title: "省级公益林(亩)",
    dataIndex: "publicForestArea",
    align: "center",
  },
  {
    title: "项目金额(万元)",
    dataIndex: "money",
    align: "center",
  },
  {
    title: "申请时间",
    dataIndex: "applicationTime",
    align: "center",
    slotName: "applicationTime",
  },
    {
    title: "状态",
    dataIndex: "tradeStatus",
    align: "center",
    slotName: "tradeStatus",
  },
  {
    title: "操作",
    dataIndex: "operations",
    align: "center",
    slotName: "operations",
    width: 200,
  },
];

// 编辑页面显示状态
const showEditPage = ref(false);
const showProcessPage = ref(false);
const currentTradeApplicationId = ref("");

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    0: 'blue',
    1: 'orange',
    2: 'purple',
    3: 'cyan',
    4: 'cyan',
    5: 'cyan',
    6: 'orange',
    7: 'green'
  };
  return colorMap[status] || 'gray';
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = tradeStatusList.value.find(item => item.code === status);
  return statusMap ? statusMap.desc : '未知状态';
}

// 获取项目类型文本
const getProjectTypeText = (type) => {
  const typeMap = projectTypeList.value.find(item => item.code === Number(type));
  return typeMap ? typeMap.desc : '未知类型';
}

// 格式化日期（年月日）
const formatDate = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '-');
}

// 格式化时间（时分秒）
const formatTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
}

// 查询数据列表
const search = () => {
  // 同步searchForm到queryParams
  queryParams.projectName = searchForm.projectName;
  queryParams.projectType = searchForm.projectType;
  queryParams.tradeStatus = searchForm.tradeStatus;
  
  loading.value = true;
  getPageTradeApplicationListApi(queryParams)
      .then((res) => {
        tableData.value = res.records || [];
        pagination.total = res.total;
        pagination.current = queryParams.pageNum;
        pagination.pageSize = queryParams.pageSize;
      })
      .catch((error) => {
        console.error('获取交易申请列表失败:', error);
        Message.error('获取交易申请列表失败');
      })
      .finally(() => {
        loading.value = false;
      });
};

// 重置查询
const reset = () => {
  // 重置searchForm
  searchForm.projectName = "";
  searchForm.projectType = null;
  searchForm.tradeStatus = null;
  
  // 重置queryParams
  queryParams.projectName = "";
  queryParams.projectType = null;
  queryParams.tradeStatus = null;
  queryParams.pageNum = 1;
  search();
};

// 分页变化
const handlePageChange = (page) => {
  queryParams.pageNum = page;
  search();
};

// 每页条数变化
const handlePageSizeChange = (pageSize) => {
  queryParams.pageSize = pageSize;
  queryParams.pageNum = 1;
  search();
};

// 新增交易申请
const handleAdd = () => {
  currentTradeApplicationId.value = "";
  showEditPage.value = true;
  showProcessPage.value = false;
};

// 编辑交易申请
const handleEdit = (row) => {
  currentTradeApplicationId.value = row.tradeApplicationId;
  showEditPage.value = true;
  showProcessPage.value = false;
};

// 处理交易申请
const handleProcess = (row) => {
  currentTradeApplicationId.value = row.tradeApplicationId;
  showEditPage.value = false;
  showProcessPage.value = true;
};

// 编辑页面取消
const handleEditCancel = () => {
  showEditPage.value = false;
  currentTradeApplicationId.value = "";
};

// 编辑页面确认
const handleEditOk = () => {
  showEditPage.value = false;
  currentTradeApplicationId.value = "";
  // 刷新列表
  search();
};

// 处理页面取消
const handleProcessCancel = () => {
  showProcessPage.value = false;
  currentTradeApplicationId.value = "";
};

// 处理页面刷新
const handleProcessRefresh = () => {
  // 刷新列表
  search();
};

// 单个删除确认
function onDeleteOK(id) {
  deleteLoading.value = true;
  deleteTradeApplicationByTradeApplicationIdApi(id)
      .then(() => {
        proxy.$message.success("删除成功");
        search();
      })
      .catch((error) => {
        proxy.$message.error("删除失败: " + error.message);
      })
      .finally(() => {
        deleteLoading.value = false;
      });
}

// 初始化
onMounted(() => {
  search();
});
</script>
<style scoped>
.address-cell, .code-cell {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.5;
  text-align: center;
  max-width: 100%;
  padding: 8px;
}

.time-cell {
  text-align: center;
  line-height: 1.4;
}

.time-detail {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}
</style>
